package com.exam.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.exam.Domain.Question;
import com.exam.Domain.Test;
import com.exam.Domain.User;
import com.exam.Service.TestService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName TestController
 * @Description
 * @Author JY
 * @Date 2020/6/3 12:50
 **/
@Controller
public class TestController {
    @Autowired
    private TestService testService;

    @ResponseBody
    @GetMapping("/backJson")
    public String backJson(@RequestParam(defaultValue = "1",required =true)Integer page){
        PageHelper.startPage(page,10);
        List<Test> testList = testService.findAllTest();
        PageInfo<Test> pageInfo = new PageInfo<>(testList);
        List<Test> tests = new ArrayList<>();
        //前台通过key值获得对应的value值
        JSONObject jobj = new JSONObject();
        //数据状态的字段名称，默认：code
        jobj.put("code",0);
        //成功的状态码，默认：0
        jobj.put("msg", "");
        jobj.put("count",testList.size());
        jobj.put("data",pageInfo.getList());
        //注意需将JSON码转为字符串格式，应使用assoc:false参数转为对象而非数组
        return jobj.toJSONString();
    }

    @ResponseBody
    @GetMapping("/myTestJson")
    public String myTestJson(@RequestParam(defaultValue = "1",required =true)Integer page,HttpSession session){
        User user =(User)session.getAttribute("user");
        String userId = user.getUserId();
        PageHelper.startPage(page,10);
        List<Test> testList = testService.findTestByUser(userId);
        PageInfo<Test> pageInfo = new PageInfo<>(testList);
        List<Test> tests = new ArrayList<>();
        //前台通过key值获得对应的value值
        JSONObject jobj = new JSONObject();
        //数据状态的字段名称，默认：code
        jobj.put("code",0);
        //成功的状态码，默认：0
        jobj.put("msg", "");
        jobj.put("count",testList.size());
        jobj.put("data",pageInfo.getList());
        //注意需将JSON码转为字符串格式，应使用assoc:false参数转为对象而非数组
        return jobj.toJSONString();
    }

    @GetMapping("/myTest")
    public String myTest(){
        return "myTest";
    }

    @GetMapping("/startTest")
    public String startTest(@RequestParam(defaultValue = "1",required =true)Integer page, HttpServletRequest req, Model model, HttpSession session){
        User user =(User)session.getAttribute("user");
        String userId = user.getUserId();
        String testId = req.getParameter("testId");
        String questionId = String.valueOf(page);
        if (testService.findIfExist(userId,testId)!=0 && testService.findExitScore(userId,testId)!=0){
            return "redirect:/resultPage?testId="+testId;
        }
        System.out.println("============开始考试=============");
        PageHelper.startPage(page,1);
        List<Question> questionList = testService.findQuestionList(req.getParameter("testId"));
        PageInfo<Question> pageInfo = new PageInfo<>(questionList);
        Test test = testService.findTestById(req.getParameter("testId"));
        if(session.getAttribute("endTime")==null||session.getAttribute("endTime")==""){
            long time = System.currentTimeMillis()-test.getTestTime().getTime()-6*60*60*1000;
            session.setAttribute("endTime",time);
        }else {
            long time = (long) session.getAttribute("endTime");
            session.setAttribute("endTime",time);
        }
        testService.insertInitScore(userId,testId);
        model.addAttribute("questions",pageInfo);
        model.addAttribute("testId",test.getTestId());
        if (testService.findResult(userId,testId,questionId)!=null){
            String word = testService.findResult(userId,testId,questionId);
            switch (word){
                case "A":
                    model.addAttribute("res",0);
                    break;
                case "B":
                    model.addAttribute("res",1);
                    break;
                case "C":
                    model.addAttribute("res",2);
                    break;
                case "D":
                    model.addAttribute("res",3);
                    break;
            }
        }
        return "testPage";
    }

    @GetMapping("/updateData")
    public void updateData(HttpServletRequest req,HttpSession session,HttpServletResponse response) {
       String testId = req.getParameter("testId");
        String questionId = req.getParameter("pageNum");
        String result = req.getParameter("result");
        User user =(User)session.getAttribute("user");
        String userId = user.getUserId();
        if (testService.findResult(userId,testId,questionId)==null){
            testService.insertTestAndQuest(result,userId,testId,questionId);
        }else {
            testService.updateTestAndQuest(result,userId,testId,questionId);
        }
        System.out.println("testId:"+testId);
        System.out.println("questionId:"+questionId);
        System.out.println("userId:"+userId);
    }

    @GetMapping("/resultPage")
    public String resultPage(@RequestParam(defaultValue = "1",required =true)Integer page,HttpServletRequest req,HttpSession session,Model model){
        User user =(User)session.getAttribute("user");
        String userId = user.getUserId();
        String testId = req.getParameter("testId");
//        考试者所填答案
        List<Question> questionList = testService.findQuestionById(testId,userId);
//        正确答案
        List<Question> questions = testService.findTrueResult(testId);
        Test test =testService.findTestById(testId);
        int all = test.getTestScore();
        List<String> differList = testService.findDifference(testId,userId);
        if (differList.size()!=0){
            for (String str :differList){
                all-=testService.findQuestScore(testId,str);
            }
        }
        for (int i=0;i<questions.size();i++){
            for (int j=0;j<questionList.size();j++){
                if (questions.get(i).getQuestionId().equals(questionList.get(j).getQuestionId())){
                    if (questions.get(i).getQuestionSolution().equals(questionList.get(j).getQuestionResult())){
                        break;
                    }
                    all-=questions.get(i).getQuestionScore();
                    break;
                }
                continue;
            }
        }
        String questionId = String.valueOf(page);
        PageHelper.startPage(page,1);
        List<Question> questList = testService.findQuestionList(req.getParameter("testId"));
        PageInfo<Question> pageInfo = new PageInfo<>(questList);
        model.addAttribute("questionList",pageInfo);
        model.addAttribute("testId",testId);
        if (testService.findResult(userId,testId,questionId)!=null){
            String word = testService.findResult(userId,testId,questionId);
            model.addAttribute("word",word);
            switch (word){
                case "A":
                    model.addAttribute("res",0);
                    break;
                case "B":
                    model.addAttribute("res",1);
                    break;
                case "C":
                    model.addAttribute("res",2);
                    break;
                case "D":
                    model.addAttribute("res",3);
                    break;
            }
        }
        testService.updateScore(userId,testId,all);
        model.addAttribute("solution",testService.findQuestionSolution(testId,questionId));
        model.addAttribute("all",all);
        return "testResult";
    }

}
